package com.cqjtu.store.user.service.impl;

import com.cqjtu.store.common.Constants;
import com.cqjtu.store.common.MD5Utils;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.user.mapper.UserMapper;
import com.cqjtu.store.user.pojo.dto.UserLogDTO;
import com.cqjtu.store.user.pojo.dto.UserRegDTO;
import com.cqjtu.store.user.pojo.entity.User;
import com.cqjtu.store.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @ProjectName: cqjtu-store
 * @Titile: UserServiceImpl
 * @Author: Lucky
 * @Description: 用户业务实现类
 */
@Service
@Transactional //开启事务
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(UserRegDTO userRegDTO) {
        // todo 判断 密码和重复密码是否一致
        if (!userRegDTO.getPassword().equals(userRegDTO.getRePassword())){
            throw new ServiceException(ServiceCode.ERR_PWD_NOTSAME,"两次密码不一致");
        }
        User existsUser =  userMapper.getUserByName(userRegDTO.getUsername());
        if(existsUser!=null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"该用户已经存在,不能重复注册.");
        }
        User user = new User();
        user.setUsername(userRegDTO.getUsername());
        String salt = UUID.randomUUID().toString().replace("-","");
        user.setSalt(salt);
        String password = MD5Utils.enctype(userRegDTO.getPassword(),salt,Constants.HASH_TIME);
        user.setPassword(password);
        //是否被删除
        user.setIsDelete(Constants.IS_NOT_DELETE);
        user.setCreatedUser(userRegDTO.getUsername());
        int result = userMapper.insert(user);
        if(result != 1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"注册用户失败");
        }

    }

    @Override
    public void login(UserLogDTO userLogDTO) {
        User existsUser =  userMapper.getUserByName(userLogDTO.getUsername());
        if(existsUser==null){
            throw new ServiceException(ServiceCode.ERR_UNAUTHORIZED,"登录失败");
        }
        String salt=existsUser.getSalt();
        String checkpwd=MD5Utils.enctype(userLogDTO.getPassword(),salt,Constants.HASH_TIME);
        if (!existsUser.getPassword().equals(checkpwd)){
            throw new ServiceException(ServiceCode.ERR_UNAUTHORIZED,"登录失败");
        }
    }
}
